/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * https://www.renren.io
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.task;

import io.renren.common.utils.*;
import io.renren.modules.noc.entity.NocMemberEntity;
import io.renren.modules.noc.entity.NocTemplateEntity;
import io.renren.modules.noc.service.NocMemberService;
import io.renren.modules.noc.service.NocTemplateService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 头条数据
 */
@Component("toutiaoTask")
public class ToutiaoTask implements ITask {
	private Logger logger = LoggerFactory.getLogger(getClass());

	//北京金诺的头条账户
	//private final String key = "NjU3STc3SzZKOEE3";
	//private final String token = "3c836e2d7125aa2c1da2787728d576d302219754";

	//青岛金诺的头条账户
	//private final String key = "QTZIMlVSMThUN0RR";
	//private final String token = "2cc3254b31139a2b792af74d28d5615d162d091f";

	@Autowired
	private NocMemberService nocMemberService;
	@Autowired
	private NocTemplateService nocTemplateService;
	@Autowired
	private MemberQRCodeUtil memberQRCodeUtil;

	@Value("${ercode.pre}")
	private String _pre;

	@Override
	public void run(String params){
		//params 参数格式 tid=1&key=xx&token=xx&startTime=2019-04-01&endTime=2019-05-11&md=备注
		String tid = UriUtil.getParamByUrl(params,"tid");
		String startTime = UriUtil.getParamByUrl(params,"startTime");
		String endTime = UriUtil.getParamByUrl(params,"endTime");
		String siteId = UriUtil.getParamByUrl(params,"siteId");
		String key = UriUtil.getParamByUrl(params,"key");
		String token = UriUtil.getParamByUrl(params,"token");
		String md = UriUtil.getParamByUrl(params,"md");

		//此三个参数不能为空
		if(StringUtils.isNotEmpty(tid)&&StringUtils.isNotEmpty(startTime)
				&&StringUtils.isNotEmpty(endTime)&&StringUtils.isNotEmpty(siteId)) {
			saveData(tid, key, token, startTime, endTime, siteId, md);
		}
	}

	//保存数据
	public void saveData(String tid,String key,String token,String startTime,String endTime,String siteId,String md){
		//NocTemplateEntity template = nocTemplateService.getById(tid);
		//String key = template.getToutiaoKey();
		//String token  = template.getToutiaoToken();

		String json = pullClues(key,token,startTime,endTime,"1","10");
		JSONObject obj = JSONObject.fromObject(json);
		String status = obj.getString("status");
		int times = 0;
		if("success".equals(status)){
			String data = obj.getString("data");
			//todo 调用保存方法
			sendMsgAndSaveData(data,tid,siteId,md);
			int count  = obj.getInt("count");
			if(count>10){
				times = count/10;
			}
			for(int i=0;i<times;i++) {
				json = pullClues(key,token,startTime, endTime, (2 + i) + "", "10");
				obj = JSONObject.fromObject(json);
				String s = obj.getString("status");
				if("success".equals(s)) {
					//todo 调用保存方法
					sendMsgAndSaveData(obj.getString("data"), tid, siteId,md);
				}
				//每次取完10条等待1s再取
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 *  发送短信 保存数据
	 * @param data  头条json数据
	 * @param tid  活动tid
	 */
	public void sendMsgAndSaveData(String data,String tid,String siteId,String md){
		try {
			JSONArray array = JSONArray.fromObject(data);
			for (int i = 0; i < array.size(); i++) {
				JSONObject obj = (JSONObject) array.get(i);
				String site_id = obj.getString("site_id");
				//判断是否是同一场展会，非同一场展会的数据直接过滤
				if(!siteId.equals(site_id)){
					continue;
				}
				String name = obj.getString("name");
				String telphone = obj.getString("telphone");
				String gender = obj.getString("gender");
				String age = obj.getString("age");
				String email = obj.getString("email");
				String remark = obj.getString("remark");
				String createTime = obj.getString("create_time");
				//自定义字段
				String remarkDict = obj.getString("remark_dict");
				Map<String, Object> p = new HashMap<>();
				p.put("col1", telphone);
				p.put("tid", tid);
				List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(p);
				if (list != null && list.size() > 0) {
					//todo 用户已经存在
				} else {
					//todo 保存数据
					NocMemberEntity member = new NocMemberEntity();
					member.setCol1(telphone);
					member.setTid(Integer.parseInt(tid));
					member.setCol3(name);
					//创建日期
					member.setCreateTime(DateUtil.timeStamp2Date(createTime));
					//vip会员
					member.setCol15("1");
					//生成二维码
					String ercode = memberQRCodeUtil.getMemberQRCode(_pre);
					if(StringUtils.isNotEmpty(ercode)){
						member.setCol20(ercode);
					}else{
						member.setCol20(_pre+"000001");
					}
					if ("1".equals(gender)) {
						member.setCol6("先生");
					} else if ("2".equals(gender)) {
						member.setCol6("女士");
					}
					member.setCol7(email);
					/*if(StringUtils.isNotEmpty(remark)) {
						member.setCol2(UriUtil.getParamByRemark(remark, "您的公司名称"));
						member.setCol13(UriUtil.getParamByRemark(remark, "您的意向展品"));
					}*/
					if(StringUtils.isNotEmpty(remarkDict)){
						JSONObject remarkDir = JSONObject.fromObject(remarkDict);
						member.setCol2(remarkDir.getString("公司名称"));
						member.setCol13(remarkDir.getString("采购意向"));
					}
                    member.setLy("toutiao");
					member.setCol10(md);
					nocMemberService.save(member);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}


	/**
	 * 调用头条接口
	 * @param startTime
	 * @param endTime
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public String pullClues(String key,String token,String startTime, String endTime, String page, String pageSize){
		Long timestap = System.currentTimeMillis() / 1000;
		String data = "/crm/v2/openapi/pull-clues/?start_time="+startTime+"&end_time="+endTime+" " + timestap;
		System.out.println(data);
		String genHMAC = HMAC_SHA1.sha256_HMAC(data, key);
		Map<String, String> headers = new HashMap<>();
		headers.put("Timestamp", timestap + "");
		headers.put("Access-Token", token);
		headers.put("Content-Type", "application/json");
		headers.put("Signature", genHMAC);

		String params = "start_time="+startTime+"&end_time="+endTime+"&page_size="+pageSize+"&page="+page;
		HttpClient client = new HttpClient();
		String str = client.sendGet("https://crm.bytedance.com/crm/v2/openapi/pull-clues/", params, headers);
		return str;
	}


}
